package com.hdax.dm.utils.token;


import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSON;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

public class Token {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private Long userId;
    //公钥
    private String publice_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxq0aEs5UDJ6laDgMMNgo0LEj4WCKIUTKqUQp0Sv0JuZYw9r+Mw9WXN5w4mkGNz7p0p6277+Jh377YPT3KgE2C3pueeZZYbd2hJbFnz8N59fcee9thpSxFLmveqnqZegP0EbzMJHXe/c2oYc7SRxWrVWnTrOVmVJgO/aunsGCtufuqwNOEkbJSnU5upNS9nETamRUjChP9SKlh1O3s7H0bO8Qs2nFY+VTjaRaHVWPuK+AQ1ne67pV6sHTCpfBXuyD3I4PVXyT8PK1vceNMUu291P7r0RjW0Bq8xGX5+PRG+gQiAeCYUfFjktB9atk1n/xg6htqdoFVmsiWWJdpPsGaQIDAQAB";

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Boolean TokenId(String tokens) {
        String token = tokens;
        RSA rsa=new RSA(null,publice_key);
        RSAPublicKey rsaPublicKey= (RSAPublicKey) rsa.getPublicKey();
        JwtParserBuilder parserBuilder= Jwts.parserBuilder();
        parserBuilder.setSigningKey(rsaPublicKey);
        JwtParser jwtParser=parserBuilder.build();
        try {
            Claims claims=jwtParser.parseClaimsJws(token).getBody();
            String id=claims.getId();
            Date date=claims.getIssuedAt();
            //从redis获取token，如果无法获取那就是token过期
            userId = Long.valueOf(id);
            return true;
        }catch (Exception ex){
           /* response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            CommonResponse commonResponse = ResponseUtils.returnFail("9999","登录超时！请重新登录");
            out.println(JSON.toJSONString(commonResponse));*/
            System.out.println("鉴权失败token");
            return false;
        }
    }

}
